package com.reason.chat.Util;

import com.alibaba.excel.EasyExcelFactory;
import com.alibaba.excel.metadata.Sheet;
import com.reason.chat.Config.ReadExcelConfig;
import com.reason.chat.pojo.Sensitive;
import org.springframework.core.io.ClassPathResource;

import java.io.IOException;
import java.io.InputStream;
import java.util.*;

/**
 * @author xfx
 */
public class ReadSensitiveThesaurus {
    public HashMap sensitiveWordMap;

    public Map initKeyWord() {
        try {
            //读取敏感词库
            Set<String> keyWordSet = sensitiveThesaurusInit();
            sensitiveThesaurusMap(keyWordSet);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return sensitiveWordMap;
    }

    public void sensitiveThesaurusMap(Set<String> keyWordSet) {
        //初始化敏感词容器，减少扩容操作
        sensitiveWordMap = new HashMap(keyWordSet.size());
        String key = null;
        Map nowMap = null;
        Map<String, String> newWorMap = null;
        //迭代keyWordSet
        Iterator<String> iterator = keyWordSet.iterator();
        while (iterator.hasNext()) {
            //关键字
            key = iterator.next();
            nowMap = sensitiveWordMap;
            for (int i = 0; i < key.length(); i++) {
                //转换成char型
                char keyChar = key.charAt(i);
                //获取
                Object wordMap = nowMap.get(keyChar);
                //如果存在该key，直接赋值
                if (wordMap != null) {
                    nowMap = (Map) wordMap;
                } //不存在则，则构建一个map，同时将isEnd设置为0，因为他不是最后一个
                else {
                    newWorMap = new HashMap<String, String>();
                    //不是最后一个
                    newWorMap.put("isEnd", "0");
                    nowMap.put(keyChar, newWorMap);
                    nowMap = newWorMap;
                }

                if (i == key.length() - 1) {
                    //最后一个
                    nowMap.put("isEnd", "1");
                }
            }
        }
    }

    public static Set<String> sensitiveThesaurusInit() throws IOException {
        Set<String> set = new HashSet<>();
        ClassPathResource SensitiveThesaurus = new ClassPathResource("static/mgck-master/敏感词库表统计.xlsx");
        InputStream StinputStream = SensitiveThesaurus.getInputStream();
        Sheet sheet = new Sheet(1, 1, Sensitive.class);
        ReadExcelConfig readExcelConfig = new ReadExcelConfig();
        EasyExcelFactory.readBySax(StinputStream, sheet, readExcelConfig);
        List<Object> sensitiveThesaurus = readExcelConfig.getSensitiveThesaurus();
        for (Object thesaurus : sensitiveThesaurus) {
            thesaurus = (Sensitive) thesaurus;
            String sensitivewords = ((Sensitive) thesaurus).getSENSITIVEWORDS();
            set.add(sensitivewords);
        }
        return set;
    }

}
